package com.gome.extract;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class SpiderDataMap {
	private Map<String, Object> dataMap = new HashMap<String, Object>();
	private JSONObject obj = new JSONObject();
	private String qualified = "";
	
	public void add(String key, Object data) {
		
		if (data instanceof List) {
			obj.put(key, listToJsonArray((List<Object>) data));
		} else if (data instanceof Map) {
			obj.put(key, mapToJsonObject((Map<String, Object>) data));
		} else {
			obj.put(key, data.toString());
		}
		
		dataMap.put(key, data);
	}
	
	private JSONObject mapToJsonObject(Map<String, Object> map) {
		JSONObject obj = new JSONObject();
		
		Set<String> keys = map.keySet();
		
		for (String key : keys) {
			Object item = map.get(key);
			if (item instanceof List) {
				obj.put(key, listToJsonArray((List<Object>) item));
			} else if (item instanceof Map) {
				obj.put(key, mapToJsonObject((Map<String, Object>) item));
			} else {
				obj.put(key, item.toString());
			}
		}
		
		return obj;
	}
	
	private JSONArray listToJsonArray(List<Object> list) {
		JSONArray array = new JSONArray();
		
		for (Object item : list) {
			if (item instanceof List) {
				array.add(listToJsonArray((List<Object>) item));
			} else if (item instanceof Map) {
				array.add(mapToJsonObject((Map<String, Object>) item));
			} else {
				array.add(item.toString());
			}
		}
		
		return array;
	}
	
	public Object get(String key) {
		return dataMap.get(key);
	}
	
	public Set<String> getKeySet() {
		return dataMap.keySet();
	}

	public String getQualified() {
		return qualified;
	}

	public void setQualified(String qualified) {
		this.qualified = qualified;
	}

	public Map<String, Object> getDataMap() {
		return dataMap;
	}
    
    public String toString() {
    	return dataMap.toString();
    }
    
    public String toJson() {
    	return obj.toString();
    }
}
